package com.atguigu.gmall.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.config.RabbitService;
import com.atguigu.gmall.pay.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.Map;

/**
 * @author 搭忆长安
 * @version 1.0
 * @date 2021年07月14日 18:21
 * @ClassName:AliPayController
 * @Description: TODO
 */
@RestController
@RequestMapping("/ali")
public class AliPayController {

    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private RabbitService rabbitService;
    /**
     * 阿里下单接口
     * @param map
     * @return
     */
    @GetMapping("/pay")
    public String aliPay(Map<String,String> map){
    return  aliPayService.aliPay(map);
    }

    /**
     * 同步回调地址
     * @param map
     * @return
     */
    @GetMapping("/callback/return")
    public String aliCallBack(@RequestParam Map<String,String> map){
        System.out.println(map);
        return "支付宝回调成功";
    }

    /**
     * 异步回调地址
     * @param map
     * @return
     */
    @RequestMapping("/callback/notify")
    public String notify(@RequestParam Map<String,String> map){
        try{
            //获取附加参数
            String passbackParams = map.get("passback_params");
            //要进行URLDecode
            String decode = URLDecoder.decode(passbackParams, "utf-8");
            //转换为map类型的数据
            Map<String,String> attachMap = JSONObject.parseObject(decode, Map.class);
            rabbitService.sendMessage(attachMap.get("exchange"),attachMap.get("routingKey"), JSONObject.toJSONString(map));
            //System.out.println(map);
            return "success";
        }catch (Exception e){
            e.printStackTrace();
            return "failure";
        }


    }

    /**
     * 校验支付结果
     * @param orderId
     * @return
     */
    @GetMapping("/checkAliPay/{orderId}")
    public String checkAluPay(@PathVariable("orderId") Long orderId){
        return aliPayService.checkAluPay(orderId);
    }

    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @GetMapping("/close/{orderId}")
    public String close(@PathVariable("orderId") Long orderId){
        return aliPayService.close(orderId);
    }

    /**
     * 退款
     * @param orderId
     * @return
     */
    @GetMapping("/refund/{orderId}")
    public String refund(@PathVariable("orderId") Long orderId){
        return aliPayService.refund(orderId);
    }
}
